package models

import (
	"errors"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/astaxie/beego/session/mysql"
	_ "github.com/astaxie/beego/session/redis"
	_ "github.com/go-sql-driver/mysql"
)

func String(v string) *string {
	return &v
}

func Byte(v byte) *byte {
	return &v
}

func Int(v int) *int {
	return &v
}

func Int16(v int16) *int16 {
	return &v
}

func Int32(v int32) *int32 {
	return &v
}

func Float64(v float64) *float64 {
	return &v
}

//常用错误类型
var (
	PASSWD_ERR = errors.New("passwd is wrong!")
)

var dataOrm orm.Ormer

func Start() {
	beego.Info("Start ORM...")
	defer beego.Info("Start ORM Finish...")
	driverName := beego.AppConfig.String("ormDriverName")
	dataSource := beego.AppConfig.String("OrmDataSource")
	orm.RegisterDriver("mysql", orm.DR_MySQL)
	orm.RegisterDataBase("default", driverName, dataSource)

	//连接数据库并创建或更新已定义的表
	beego.BeeLogger.Info("connect database; drvername:%s, datasource:%s;", driverName, dataSource)
	err := orm.RunSyncdb("default", false, true)
	if err != nil {
		panic(err)
	}
	dataOrm = orm.NewOrm()

	//创建必要的表
	_, err = dataOrm.Raw(`create table if not exists friend (
				user_id int(11) NOT NULL,
				friend_id int(11) NOT NULL,
				remark varchar(255) DEFAULT NULL,
				KEY user_id (user_id)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8;`).Exec()
	if err != nil {
		panic("create table friend error:" + err.Error())
	}

	if beego.SessionProvider == "mysql" {
		// mysql session support need create table:
		beego.BeeLogger.Info("SessionProvider is mysql; Start table of session to create ")
		_, err := dataOrm.Raw(`CREATE TABLE IF NOT EXISTS session (
			session_key char(64) NOT NULL,
			session_data blob,
			session_expiry int(11) unsigned NOT NULL,
			PRIMARY KEY (session_key)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8`).Exec()
		if err != nil {
			panic("create table session error:" + err.Error())
		}
		beego.BeeLogger.Info("SessionProvider is mysql; End table of session to create ")
	}
}
